# -*- coding: utf-8 -*-
import time 
# to manage mavlink data 
'''
    data structure:
    list(
        mavlink_message_t: dict(
            'len':
            'seq':
            'sysid':
            'compid':
            'msgid':
            'payload':
            'crc':
        )
    )
'''

class dataManager(object):
    def __init__(self,data=None):
        if data is None:
            data = list()
        self.data = data
        self.msgAmountOfID = list()
    
    def push(self,data):
        '''
            add data to its buffer 
        '''
        self.data.append(data)
    
    def clear(self):
        self.data = list()
    

class mavlinkDataManager(dataManager):
    def __init__(self,data=None):
        dataManager.__init__(self,data)
        self.startTime = None
        self.mavlinkCount = 0
        # data receive time list for each msgID
        # key : sysID, val: dict: key: msgID val: list of received time
        self.dataReceiveTimeList=dict()
        self.dataReceiveLenList=dict()
        self.dataReceiveCount_of_sysID=dict()
        self.pkgReceiveCount_of_sysID=dict()
    def startTimer(self):
        '''
            start timer
        '''
        self.startTime = time.time()
        
    def push(self,msgs):
        if type(msgs) is not  list:
            msgs = [msgs]
        timeNow = time.time()
        self.mavlinkCount  = self.mavlinkCount + len(msgs)
        for msg in msgs:
            dataManager.push(self,msg)
            sysID = msg['sysid']
            if self.dataReceiveTimeList.has_key(sysID):
                msgID = msg['msgid']
                if self.dataReceiveTimeList[sysID].has_key(msgID):
                    self.dataReceiveTimeList[sysID][msgID].append(timeNow)
                    self.dataReceiveLenList[sysID][msgID].append(msg['len']+8)
                else:
                    self.dataReceiveTimeList[sysID][msgID]=[timeNow]
                    self.dataReceiveLenList[sysID][msgID]=[msg['len']+8]
                self.dataReceiveCount_of_sysID[sysID] += msg['len']+8
                self.pkgReceiveCount_of_sysID[sysID] += 1
            else:
                self.dataReceiveCount_of_sysID[sysID] = msg['len']+8
                self.pkgReceiveCount_of_sysID[sysID]  = 1
                msgID = msg['msgid']
                self.dataReceiveTimeList[sysID]={msgID:[timeNow]} 
                self.dataReceiveLenList[sysID] ={msgID:[msg['len']+8]} 

    
    def clear(self):
        dataManager.clear(self)
        self.dataReceiveTimeList=dict()
        self.dataReceiveLenList=dict()
        self.dataReceiveCount_of_sysID= dict()
        self.pkgReceiveCount_of_sysID = dict()
